package com.kun.portal.webframe.service;

import com.kun.portal.webframe.dao.DutyDao;
import com.kun.portal.webframe.dao.EquipmentDao;
import com.kun.portal.webframe.po.EquipmentPo;
import com.kun.portal.webframe.util.PageImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.Pageable;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Collections;
import java.util.Date;

/**
 * Created by Administrator on 2018/7/6.
 */
@Service
public class EquipmentService {
    @Autowired
    private EquipmentDao equipmentDao;
    @Autowired
    private EntityManager entityManager;


    public Page<EquipmentPo> find(String filter, String status, Pageable pageable){
        if(StringUtils.isNotBlank(filter)||StringUtils.isNotBlank(status)){
            return equipmentDao.findAll(new Specification<EquipmentPo>() {
                @Override
                public Predicate toPredicate(Root<EquipmentPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                    if(StringUtils.isNotBlank(status)){
                        Predicate predicate = cb.equal(root.get("status"),status);
                        if(StringUtils.isNotBlank(filter)){
                            Predicate predicate1 =cb.like(root.get("equipmentName"),"%"+filter+"%");
                            Predicate predicate2 = cb.like(root.get("equipmentNum"),"%"+filter+"%");
                            return query.where(cb.or(predicate1,predicate2),predicate).getRestriction();
//                            return cb.or(cb.and(predicate,predicate1),cb.and(predicate,predicate2));
                        }
                        return cb.and(predicate);
                    }
                    return cb.or(cb.like(root.get("equipmentName"),"%"+filter+"%"),cb.like(root.get("equipmentNum"),"%"+filter+"%"));

                }
            },pageable);
        }else{
            Page<EquipmentPo> page =equipmentDao.findAll(pageable);
            return page;
        }

         //Query query=entityManager.createQuery("select e from EquipmentPo e inner join fetch  e.repairPlaneSettings inner join fetch  e.maintenancePlanSettings");
//         return new PageImpl<EquipmentPo>(query,pageable);
    }
}
